package cn.com.winning.ecare.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.winning.ecare.activity.R.color;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.expandable.ActionSlideExpandableListView;
import cn.com.winning.ecare.utils.DisplayUtil;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.URLUtils;
import cn.com.winning.ecare.utils.UserRecord;
import cn.com.winning.ecare.widgets.CustomProgressDialog;
import cn.com.winning.ecare.widgets.InnerListView;

/**
 * 检验报告
 */

public class TjbgmxActivity extends Activity
{

	private ListView list_sub;
	private ActionSlideExpandableListView list_main;
	private TextView content, item, reference;
	private List<Map<String, Object>> listmain = new ArrayList<Map<String, Object>>();
	private List<Map<String, Object>> listsub = new ArrayList<Map<String, Object>>();
	private List<Object> children = new ArrayList<Object>();
	MyMainAdapter mainAdapter = null;
	MySubAdapter subAdapter = null;
	MyApplication myApplication;
	CustomProgressDialog proDialog;// 加载框
	TjbgmxActivity oThis = this;
	private String tjbh="";
	private ImageButton menuButton;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.tjbgmx);
		tjbh=getIntent().getStringExtra("tjbh");
		myApplication = (MyApplication) getApplication();
		myApplication.addActivity(this);
		myApplication = (MyApplication) getApplication();
		myApplication.addActivity(this);
		myApplication.addActivity(this);
		myApplication.getUserRecords().setUsername(myApplication.getAccount());
		myApplication.getUserRecords().setModule("TjbgmxActivity@体检报告明细");
		UserRecord.getInstance(myApplication.getUserRecords()).init();
		findViews();
		getInfo();
	}

	private void findViews()
	{
		list_main = (ActionSlideExpandableListView) findViewById(R.id.list);
		menuButton = (ImageButton) findViewById(R.id.menuButton);

		menuButton.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{

				oThis.onBackPressed();
			}
		});
	}

	Handler myHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what)
			{
				case -1:
					proDialog.dismiss();
					Toast.makeText(oThis, (String)msg.obj, Toast.LENGTH_SHORT).show();
					if (mainAdapter != null)
					{
						mainAdapter.notifyDataSetChanged();
					}
					break;
				case 0:
					if (proDialog != null && proDialog.isShowing())
					{
						proDialog.dismiss();
					}
					Map<String, Object> map = (Map<String, Object>) msg.obj;
					listmain = (List<Map<String, Object>>) map.get("tempmain");
					children = (List<Object>) map.get("tempchildren");
					if (mainAdapter == null)
					{
						mainAdapter = new MyMainAdapter();
					}
					list_main.setAdapter(mainAdapter);
					mainAdapter.notifyDataSetChanged();

					break;
				case 1:

					break;
				case 2:

					break;
				default:
					break;
			}
		}
	};

	private void getInfo()
	{
		proDialog = CustomProgressDialog.createDialog(oThis);
		proDialog.setMessage("数据加载中...");
		proDialog.show();
		proDialog.setCanceledOnTouchOutside(false);
		// 这里单开一个线程和后台数据交互
		new Thread(new LoadData()).start();

	}

	class LoadData implements Runnable
	{

		public void run()
		{
			// TODO Auto-generated method stub
			Looper.prepare();
			initData();
			Looper.loop();

		}

	}

	private void initData()
	{
		try
		{
			Message msg = myHandler.obtainMessage();
//			Intent intent = getIntent();
//			String startDate = intent.getStringExtra("startDate").replace("-", "").replace("-", "");
//			String endDate = intent.getStringExtra("endDate").replace("-", "").replace("-", "");
			List<NameValuePair> ls = new ArrayList<NameValuePair>();
			ls.add(new BasicNameValuePair("userid", myApplication.getAccount() == null ? "" : myApplication.getAccount()));
			ls.add(new BasicNameValuePair("tjbh", tjbh));
//			ls.add(new BasicNameValuePair("sfzh",myApplication.getSfzh()));
//			ls.add(new BasicNameValuePair("zsxm",myApplication.getHzxm()));
//			ls.add(new BasicNameValuePair("sjh",myApplication.getSjh()));
//			ls.add(new BasicNameValuePair("startdate", startDate));
//			ls.add(new BasicNameValuePair("enddate", endDate));
			JSONObject json = HTTPGetTool.getTool().post(URLUtils.HOST + URLUtils.URLFINDJYBGXX, ls);
			JSONArray jsonArr;
			List<Map<String, Object>> tempmain = new ArrayList<Map<String, Object>>();
			List<Object> tempchildren = new ArrayList<Object>();
			Map<String, Object> tempmap = new HashMap<String, Object>();
			if (json != null)
			{
				if (!json.toString().equals("{\"msg\":\"系统错误！\",\"success\":\"false\"}"))
				{
					if (new JSONArray(json.getString("jsonstr")).length() > 0)
					{
						jsonArr = new JSONArray(json.getString("jsonstr"));
						List<Map<String, Object>> list;
						for (int i = 0; i < jsonArr.length(); i++)
						{
							JSONObject obj_main = jsonArr.getJSONObject(i);
							Map<String, Object> map_main = new HashMap<String, Object>();
							map_main.put("id", obj_main.getString("id"));
							map_main.put("bglx", obj_main.getString("bglx"));
							map_main.put("bgid", obj_main.getString("bgid"));
							map_main.put("jcsj", obj_main.getString("jcsj"));
							map_main.put("hzxm", obj_main.getString("hzxm"));
							map_main.put("ch", obj_main.getString("ch"));
							map_main.put("sqys", obj_main.getString("sqys"));
							map_main.put("bgys", obj_main.getString("bgys"));
							map_main.put("shys", obj_main.getString("shys"));
							map_main.put("userid", obj_main.getString("userid"));
							JSONArray js = new JSONArray(obj_main.getString("bgmxxx"));
							list = new ArrayList<Map<String, Object>>();
							for (int j = 0; j < js.length(); j++)
							{
								JSONObject obj_sub = js.getJSONObject(j);
								Map<String, Object> map_sub = new HashMap<String, Object>();
								map_sub.put("sfdx", obj_sub.getString("sfdx"));
								map_sub.put("jcxm", obj_sub.getString("jcxm"));
								map_sub.put("jcbw", obj_sub.getString("jcbw"));
								list.add(map_sub);
							}
							Map<String, Object> map_temp = new HashMap<String, Object>();
							map_temp.put("sfdx", "项目");
							map_temp.put("jcxm", "结果");
							map_temp.put("jcbw", "参考值");
							list.add(0, map_temp);
							tempmain.add(map_main);
							tempchildren.add(list);
						}
						msg.what = 0;
						tempmap.put("tempmain", tempmain);
						tempmap.put("tempchildren", tempchildren);
						msg.obj = tempmap;
					}
					else
					{
						msg.what = -1;
						msg.obj = "暂无数据";
					}

				}
				else
				{
					msg.what = -1;
					msg.obj = "暂无数据";
				}
			}
			else
			{
				msg.what = -1;
				msg.obj = "网络连接失败!";
			}
			myHandler.sendMessage(msg);
		}
		catch (Exception e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 自定义listview布局显示内容
	 * 
	 * @author zjj
	 */
	class MyMainAdapter extends BaseAdapter
	{

		public int getCount()
		{
			// TODO Auto-generated method stub
			return listmain.size();
		}

		public Object getItem(int position)
		{
			// TODO Auto-generated method stub
			return listmain.get(position);
		}

		public long getItemId(int position)
		{
			// TODO Auto-generated method stub
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent)
		{
			// TODO Auto-generated method stub
			View view = convertView;
			Map<String, Object> map = (Map<String, Object>) getItem(position);
			view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.tjbgmx_main, null);
			TextView reportName = (TextView) view.findViewById(R.id.reportName);
			TextView reportTime = (TextView) view.findViewById(R.id.reportTime);

			TextView reportDoctor = (TextView) view.findViewById(R.id.reportDoctor);

			reportName.setText(map.get("bglx").toString());

			String time = map.get("jcsj").toString();
//			time = map.get("jcsj").toString().substring(0, 4) + "-" + map.get("jcsj").toString().substring(4, 6) + "-"
//					+ map.get("jcsj").toString().substring(6, 8);
			reportTime.setText(time);

			reportDoctor.setText(map.get("bgys").toString());

			InnerListView list_sub = (InnerListView) view.findViewById(R.id.list_checkout_sub);
			ScrollView scroll_view = (ScrollView) view.findViewById(R.id.scroll_view);
			listsub = (List<Map<String, Object>>) children.get(position);
			subAdapter = new MySubAdapter(oThis, listsub);
			list_sub.setAdapter(subAdapter);
			list_sub.setParentScrollView(scroll_view);
			list_sub.setMaxHeight(DisplayUtil.dip2px(oThis, 300));
			return view;
		}

	}

	/**
	 * 自定义listview布局显示内容
	 */
	class MySubAdapter extends BaseAdapter
	{

		Context context;
		List children;

		public MySubAdapter(Context context, List children)
		{
			super();
			this.context = context;
			this.children = children;
		}

		public int getCount()
		{
			// TODO Auto-generated method stub
			return children.size();
		}

		public Object getItem(int position)
		{
			// TODO Auto-generated method stub
			return children.get(position);
		}

		public long getItemId(int position)
		{
			// TODO Auto-generated method stub
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent)
		{
			// TODO Auto-generated method stub
			View view = convertView;
			Map<String, Object> map = (Map<String, Object>) getItem(position);
			view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.tjbgmx_sub, null);
			item = (TextView) view.findViewById(R.id.item);
			item.setText(map.get("sfdx").toString());

			content = (TextView) view.findViewById(R.id.content);
			content.setText(map.get("jcxm").toString());
			if(map.get("jcxm").toString().length()>0){
				if ("↑".equals(map.get("jcxm").toString().substring(map.get("jcxm").toString().length() - 1))
						|| "↓".equals(map.get("jcxm").toString().substring(map.get("jcxm").toString().length() - 1)))
				{
					content.setTextColor(Color.RED);
				}
			}
			

			reference = (TextView) view.findViewById(R.id.reference);
			reference.setText(map.get("jcbw").toString());
			if (position % 2 == 1)
			{
				view.setBackgroundColor(getResources().getColor(R.color.tabbg));
			}
			else
			{

			}

			return view;
		}

	}

}
